package baidumodel.listener;


import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

import java.util.Objects;

/**
 * 百度文心一言
 * 使用流式请求api时，用户可以自定义监听类，继承 {@link BaiduEventSourceListener}，或者继承 {@link EventSourceListener}
 * 可以参考本类的实现，在 {@link BaiduEventSourceListener#onEvent(EventSource, String, String, String)} 方法中中接收数据，实现自己的业务逻辑；
 */
public class BaiduEventSourceListener extends EventSourceListener {

    @Override
    public void onOpen(EventSource eventSource, Response response) {
        System.out.println("baidu建立sse连接... \n");
    }

    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {
        System.out.println("baidu返回数据：" + data + " \n");
    }

    @Override
    public void onClosed(EventSource eventSource) {
        System.out.println("baidu关闭sse连接... \n");
    }

    @SneakyThrows
    @Override
    public void onFailure(EventSource eventSource, Throwable t, Response response) {
        if(Objects.isNull(response)){
            System.out.println("baidu  sse连接异常:{} \n" + t);
            eventSource.cancel();
            return;
        }
        ResponseBody body = response.body();
        if (Objects.nonNull(body)) {
            System.out.printf("baidu  sse连接异常data：%s%n \n",  body.string());
        } else {
            System.out.printf("baidu  sse连接异常data：%s%n \n", response);
        }
        System.out.printf("baidu sse 连接异常，异常信息：%s \n", t.getMessage());
        eventSource.cancel();
    }
}
